//
//  IDFAUtils.m
//  Peso Guide
//
//  Created by macbook on 2025/6/6.
//

#import "IDFAUtils.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>

@implementation IDFAUtils

// 请求IDFA权限并获取IDFA
+ (void)requestIDFAPermissionWithCompletion:(void (^)(NSString *idfa, BOOL isTrackingAuthorized))completion {
    if (@available(iOS 14, *)) {
        // 检查跟踪授权状态
        ATTrackingManagerAuthorizationStatus status = [ATTrackingManager trackingAuthorizationStatus];
        
        if (status == ATTrackingManagerAuthorizationStatusNotDetermined) {
            // 未决定 - 请求权限
            [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self handleTrackingStatus:status completion:completion];
                });
            }];
        } else {
            // 已决定状态
            [self handleTrackingStatus:status completion:completion];
        }
    } else {
        // iOS 14 以下系统
        [self handlePreiOS14TrackingWithCompletion:completion];
    }
}

// 处理跟踪状态
+ (void)handleTrackingStatus:(ATTrackingManagerAuthorizationStatus)status
                  completion:(void (^)(NSString *idfa, BOOL isTrackingAuthorized))completion {
    BOOL authorized = (status == ATTrackingManagerAuthorizationStatusAuthorized);
    NSString *idfa = authorized ? [self getIDFA] : @"";
    
    if (completion) {
        completion(idfa, authorized);
    }
}

// 处理 iOS 14 以下系统
+ (void)handlePreiOS14TrackingWithCompletion:(void (^)(NSString *idfa, BOOL isTrackingAuthorized))completion {
    BOOL trackingEnabled = [[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled];
    NSString *idfa = trackingEnabled ? [self getIDFA] : @"";
    
    if (completion) {
        completion(idfa, trackingEnabled);
    }
}

// 直接获取IDFA（不请求权限）
+ (NSString *)getIDFA {
    if (@available(iOS 14, *)) {
        if ([ATTrackingManager trackingAuthorizationStatus] != ATTrackingManagerAuthorizationStatusAuthorized) {
            return @"";
        }
    } else {
        if (![[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            return @"";
        }
    }
    
    NSUUID *idfa = [[ASIdentifierManager sharedManager] advertisingIdentifier];
    return [idfa UUIDString];
}

// 检查是否已授权跟踪
+ (BOOL)isTrackingAuthorized {
    if (@available(iOS 14, *)) {
        return [ATTrackingManager trackingAuthorizationStatus] == ATTrackingManagerAuthorizationStatusAuthorized;
    } else {
        return [[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled];
    }
}

// 检查IDFA是否可用
+ (BOOL)isIDFAAvailable {
    Class atClass = NSClassFromString(@"ATTrackingManager");
    Class asClass = NSClassFromString(@"ASIdentifierManager");
    return (atClass != nil || asClass != nil);
}

@end
